<script setup>
import courseApi from "@/api/course.js";
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import reserveApi from "@/api/reserve.js";
import { useUserInfoStore } from "@/store/userInfo.js";

const userInfoStore = useUserInfoStore();

// 数据表格
const list = ref([]);
const total = ref(0);

// 分页信息
const courseQuery = ref({
  page: 1,
  limit: 10,
});

// 加载课程数据和预约状态
const loadData = async () => {
  try {
    // 1. 拉课程列表
    const courseRes = await courseApi.list(courseQuery.value);
    if (courseRes.code !== 0) {
      ElMessage.error(courseRes.msg);
      return;
    }

    const courses = courseRes.data.records;
    total.value = courseRes.data.total;

    const userId = userInfoStore.userId;
    if (!userId) {
      list.value = courses.map(c => ({ ...c, reserved: false }));
      return;
    }

    // 2. 拉当前用户预约记录
    const reserveRes = await reserveApi.list({
      userId,
      page: 1,
      limit: 20,
    });

    const reservedCourseIds = (reserveRes.code === 0 ? reserveRes.data.records : []).map(r => r.courseId);

    // 3. 标记课程是否已预约
    list.value = courses.map(c => ({
      ...c,
      reserved: reservedCourseIds.includes(c.id)
    }));

  } catch (e) {
    console.error(e);
    ElMessage.error("加载课程失败，请稍后重试");
  }
};
loadData();

// 点击预约按钮
const showUpdateDialog = async (row) => {
  if (!row || !row.id) {
    ElMessage.error("未获取到课程ID");
    return;
  }

  const userId = userInfoStore.userId;
  if (!userId) {
    ElMessage.error("请先登录再预约");
    return;
  }

  if (row.reserved) {
    ElMessage.warning("您已预约过该课程");
    return;
  }

  try {
    await ElMessageBox.confirm("您确认要预约这门课程么?", "警告", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    });

    const res = await reserveApi.add({ courseId: row.id, userId });
    if (res.code === 0) {
      ElMessage.success(res.msg || "预约成功");
      // 标记当前行已预约
      row.reserved = true;
    } else {
      ElMessage.error(res.msg || "预约失败");
    }
  } catch (e) {
    if (e !== "cancel" && e !== "close") {
      console.error(e);
      ElMessage.error("操作失败，请稍后重试");
    }
  }
};
</script>

<template>
  <el-card>
    <template #header>
      <div class="header">
        <span style="font-weight: bold; font-size: 16px">课程信息</span>
      </div>
    </template>

    <el-table :data="list" style="width: 100%" :row-style="{ height: '80px' }">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="课程名称" width="120" />
      <el-table-column prop="coachName" label="教练" width="150" />
      <el-table-column prop="time" label="课程时间" width="180" />
      <el-table-column prop="length" label="时长(分钟)" width="150" />
      <el-table-column prop="maxCount" label="最大人数" width="150" />
      <el-table-column prop="room" label="教室" width="120" />
      <el-table-column prop="image" label="封面" width="180">
        <template #default="{ row }">
          <img
              v-if="row.image"
              :src="row.image"
              style="max-height: 60px; max-width: 120px; object-fit: cover"
          />
        </template>
      </el-table-column>

      <el-table-column align="center" width="150" fixed="right" label="操作">
        <template #default="{ row }">
          <el-button
              size="small"
              type="success"
              :disabled="row.reserved"
              @click="showUpdateDialog(row)"
          >
            {{ row.reserved ? "已预约" : "预约" }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-model:current-page="courseQuery.page"
        v-model:page-size="courseQuery.limit"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @change="loadData"
        style="margin-top: 20px; justify-content: flex-end"
    />
  </el-card>
</template>

<!--<script setup>
import courseApi from "@/api/course.js";
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import reserveApi from "@/api/reserve.js";
import { useUserInfoStore } from "@/store/userInfo.js";

const userInfoStore = useUserInfoStore();

// 数据表格
const list = ref([]);
const total = ref(0);

// 分页信息
const courseQuery = ref({
  page: 1,
  limit: 10,
});

// 加载课程数据
const loadData = () => {
  courseApi.list(courseQuery.value).then((result) => {
    if (result.code === 0) {
      list.value = result.data.records;
      total.value = result.data.total;
    } else {
      ElMessage.error(result.msg);
    }
  });
};
loadData();

// 点击预约按钮
const showUpdateDialog = async (row) => {
  if (!row || !row.id) {
    ElMessage.error("未获取到课程ID");
    return;
  }

  const userId = userInfoStore.userId;
  if (!userId) {
    ElMessage.error("请先登录再预约");
    return;
  }

  try {
    // 先查 reserve 表里有没有记录（这里调用查询接口）
    const checkRes = await reserveApi.list({
      courseId: row.id,
      userId,
      page: 1,
      limit: 10,
    });

    if (checkRes.code === 0 && checkRes.data.records.length > 0) {
      ElMessage.warning("您已预约过该课程");
      return;
    }

    // 没预约过 -> 弹窗确认
    await ElMessageBox.confirm("您确认要预约这门课程么?", "警告", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 提交预约
    const payload = { courseId: row.id, userId };
    const res = await reserveApi.add(payload);

    if (res.code === 0) {
      ElMessage.success(res.msg || "预约成功");
      // 可选：刷新表格
      loadData();
    } else {
      ElMessage.error(res.msg || "预约失败");
    }
  } catch (e) {
    if (e !== "cancel" && e !== "close") {
      console.error(e);
      ElMessage.error("操作失败，请稍后重试");
    }
  }
};
</script>

<template>
  <el-card>
    <template #header>
      <div class="header">
        <span style="font-weight: bold; font-size: 16px">课程信息</span>
      </div>
    </template>

    &lt;!&ndash; 表格展示 &ndash;&gt;
    <el-table :data="list" style="width: 100%" :row-style="{ height: '80px' }">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="课程名称" width="120" />
      <el-table-column prop="coachName" label="教练" width="100" />
      <el-table-column prop="time" label="课程时间" width="180" />
      <el-table-column prop="length" label="时长(分钟)" width="120" />
      <el-table-column prop="maxCount" label="最大人数" width="120" />
      <el-table-column prop="room" label="教室" width="120" />
      <el-table-column prop="image" label="封面" width="180">
        <template #default="{ row }">
          <img
              v-if="row.image"
              :src="row.image"
              style="max-height: 60px; max-width: 120px; object-fit: cover"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" width="200px" fixed="right" label="操作">
        <template #default="{ row }">
          <el-button size="small" type="success" @click="showUpdateDialog(row)">
            预约
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    &lt;!&ndash; 分页 &ndash;&gt;
    <el-pagination
        v-model:current-page="courseQuery.page"
        v-model:page-size="courseQuery.limit"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @change="loadData"
        style="margin-top: 20px; justify-content: flex-end"
    />
  </el-card>
</template>-->

<style>
/* 调整 el-switch 尺寸 */
.custom-switch .el-switch__core {
  border-radius: 16px; /* 圆角更平滑 */
  font-size: 14px;
  position: relative;
}

/* 内部文字居中 */
.custom-switch .el-switch__core::after {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #fff;
  font-size: 13px;
  font-weight: 600;
  white-space: nowrap;
  pointer-events: none; /* 避免挡点击 */
}

/* 开启状态：绿色，可预约 */
.custom-switch.is-checked .el-switch__core::after {
  content: "可预约";
}

/* 关闭状态：红色，已满员 */
.custom-switch:not(.is-checked) .el-switch__core::after {
  content: "已预约";
}

</style>
